package com.example.qt.ptplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qt.ptplatform.entity.Torrent;
import com.example.qt.ptplatform.service.TorrentService;
import com.example.qt.ptplatform.service.impl.SeedServiceImpl;
import com.example.qt.ptplatform.utils.JsonResult;
import com.turn.ttorrent.common.TorrentFile;
import com.turn.ttorrent.common.TorrentMetadata;
import com.turn.ttorrent.common.TorrentParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "seed")
public class SeedController {

    @Autowired
    private SeedServiceImpl seedService;
    @Autowired
    private TorrentService torrentService;  // 添加 TorrentService，用于处理种子相关的数据库操作

    // 接口：处理添加种子记录的请求
    @PostMapping("/addSeed")
    public JsonResult addSeed(@RequestParam("file") MultipartFile file,
                              @RequestParam("user_id") int userId,
                              @RequestParam("title") String title,
                              @RequestParam("description") String description,
                              @RequestParam("tags") String tags,
                              @RequestParam("category") String category) {
        try (InputStream is = file.getInputStream()) {
            // 解析种子文件
            TorrentMetadata metadata = new TorrentParser().parse(file.getBytes());

            // 检查种子是否已存在
            LambdaQueryWrapper<Torrent> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(Torrent::getInfoHash, metadata.getHexInfoHash());
            //if (torrentService.count(wrapper) > 0) {
                //return JsonResult.error("种子已存在");
            //}

            // 创建新的种子对象
            Torrent torrent = new Torrent();
            String paths =file.getOriginalFilename();
            Long size = metadata.getFiles().stream().map(f -> f.size).reduce(0L, Long::sum);

            // 设置种子信息
            torrent.setTitle(title);
            torrent.setUserId(userId);
            torrent.setSizeGB(size / 1024.0 / 1024.0 / 1024.0); // 转换为GB
            torrent.setRealFilename(paths);
            torrent.setInfoHash(metadata.getHexInfoHash());
            String hexInfoHash = metadata.getHexInfoHash();
            torrent.setInfoHash(hexInfoHash);
            torrent.setUploadTime(LocalDateTime.now());
            torrent.setDescription(description != null ? description : metadata.getComment().orElse(""));
            torrent.setTags(tags);
            torrent.setCategory(category);

            // 保存种子到数据库
            torrentService.save(torrent);

            // 获取积分和info_hash
            SeedServiceImpl.UploadResult result = seedService.addSeed(file,torrent);
            LambdaQueryWrapper<Torrent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Torrent::getInfoHash,hexInfoHash).orderByDesc(Torrent::getUploadTime);
            List<Torrent> torrents = new ArrayList<>();
            Map<String, Object> data = new HashMap<>();
            try {
//                20250529修改
                torrents = torrentService.list(lambdaQueryWrapper);
                if (torrents !=null && !torrents.isEmpty()) {
                    data.put("id",torrents.get(0).getTorrentId() );
                }

            } catch (Exception e) {
                return JsonResult.error("封面以无法上传");
            }
            data.put("points", result.getEarnedPoints());
            data.put("info_hash", metadata.getHexInfoHash());
            return JsonResult.success(200, "种子上传成功", data);
        } catch (IOException e) {
            // 异常处理
            return JsonResult.error("上传失败", e.getMessage());
        }
    }
}
